package template

import (
	"bytes"
	"html/template"

	"github.com/spf13/viper"

	"bbs/pkg/domain"
)

type emailTempate struct {
	Path string
}

type templateService struct {
	emailTemp *emailTempate
}

func NewTemplateService() domain.TemplateService {
	emailTemp := &emailTempate{
		Path: viper.GetString("template.email_path"),
	}
	return &templateService{
		emailTemp: emailTemp,
	}
}

func (svc *templateService) RenderCaptchaTemplate(code string) (string, error) {
	return svc.renderEmailCaptchaTemplate(code)
}

func (svc *templateService) renderEmailCaptchaTemplate(code string) (string, error) {
	t, err := template.ParseFiles(svc.emailTemp.Path)
	if err != nil {
		return "", nil
	}

	buf := bytes.NewBuffer(nil)
	d := struct {
		Code string
	}{
		Code: code,
	}
	err = t.ExecuteTemplate(buf, "captcha", d)

	return buf.String(), err
}
